package com.kapcb.assemble.filter;

import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.function.BiConsumer;

/**
 * <a>Title: AbstractFilterExecutor </a>
 * <a>Author: Kapcb <a>
 * <a>Description: AbstractFilterExecutor <a>
 *
 * @author Kapcb
 * @version 1.0
 * @date 2024/4/18 21:11
 * @since 1.0
 */
public abstract class AbstractFilterExecutor implements FilterAssembleExecutor {

    @Override
    public void execute(String type, FilterRequest request, FilterResponse response) {
        valid(type, request, response);
        List<Filter> filters = selectFilter(type);
        FilterChain filterChain = CFilterChain.FilterChainBuilder.newBuilder()
                .addFilters(filters).build();
        filterChain.doFilter(request, response);
    }

    @Override
    public void execute(String type, FilterRequest request, FilterResponse response, BiConsumer<FilterRequest, FilterResponse> targetMethod) {
        valid(type, request, response);
        List<Filter> filters = selectFilter(type);
        FilterChain filterChain = CFilterChain.FilterChainBuilder.newBuilder()
                .addFilters(filters).addTargetMethod(targetMethod).build();
        filterChain.doFilter(request, response);
    }

    protected void valid(String type, FilterRequest request, FilterResponse response) {
        if (StringUtils.isBlank(type) || Objects.isNull(request) || Objects.isNull(response)) {
            throw new IllegalArgumentException("method transfer var error, pls check your code!");
        }
    }

    /**
     * 选择过滤器
     *
     * @param type
     * @return 过滤器链
     */
    protected abstract List<Filter> selectFilter(String type);

}
